#include "Application.h"
#include <iostream>
#include <fstream>
#include <sys/stat.h>

PF::Application::Application()
{
}

PF::Application::~Application()
{
	std::cout << "Quitting SDL.\n";
	SDL_Quit();
}

bool PF::Application::Init(const char *a_szTitle, int a_iX, int a_iY,int a_iW, int a_iH, Uint32 a_uiFlags)
{
   // --------------------------------------------------------------------------
   // This makes relative paths work in C++ in Xcode by changing directory to 
   // the Resources folder inside the .app bundle
   // Referenced from Stack Overflow: http://cl.ly/2E0a052s1n2q2p2X0330
   
   #ifdef __APPLE__    
   CFBundleRef mainBundle = CFBundleGetMainBundle();
   CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
   char path[PATH_MAX];
   if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, 
                                         PATH_MAX))
   {
      // error!
   }
   CFRelease(resourcesURL);
   
   chdir(path);
   
   // do not remove this yet. i need this for debugging.
   std::cout << "Current Path: " << path << std::endl;
   if(FileExists("./images/DefaultSkin.png"))
      std::cout << "YARLY\n";
   else
      std::cout << "NOWAI\n";
   
   #endif
   // --------------------------------------------------------------------------
   std::cout << "Initializing SDL.\n";

   if(SDL_Init(SDL_INIT_EVERYTHING) == -1)
   {
	   std::cout << "Could not initialize SDL: " << SDL_GetError() << ".\n";
	   return 0;
   }

   std::cout << "SDL initialized.\n";

   return m_kWindow.Create(a_szTitle, a_iX, a_iY, a_iW, a_iH, a_uiFlags);
}

void PF::Application::Run()
{
	m_kTimer.Reset();

	while(true)
	{
		float fDeltaTime = m_kTimer.GetElapsedTime();
		m_kTimer.Reset();

		m_kWindow.Update(fDeltaTime);
		m_kWindow.Render();
	}
}

PF::Window *PF::Application::GetWindow()
{
	return &m_kWindow;
}

bool PF::Application::FileExists(std::string strFilename) { 
   struct stat stFileInfo; 
   bool blnReturn; 
   int intStat; 
   
   // Attempt to get the file attributes 
   intStat = stat(strFilename.c_str(),&stFileInfo); 
   if(intStat == 0) { 
      // We were able to get the file attributes 
      // so the file obviously exists. 
      blnReturn = true; 
   } else { 
      // We were not able to get the file attributes. 
      // This may mean that we don't have permission to 
      // access the folder which contains this file. If you 
      // need to do that level of checking, lookup the 
      // return values of stat which will give you 
      // more details on why stat failed. 
      blnReturn = false; 
   } 
   
   return(blnReturn); 
}

